package com.yxr.affairs;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.os.PowerManager;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.AutoCompleteTextView;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;

import com.thoughtworks.xstream.XStream;
import com.yxr.affairs.api.Constans1;
import com.yxr.affairs.base.BaseActivity1;
import com.yxr.affairs.bean1.Data;
import com.yxr.affairs.bean1.Param1;
import com.yxr.affairs.bean1.Storeditem;
import com.yxr.affairs.utils.CommonProgressDialog;
import com.yxr.affairs.utils.SPUtils;
import com.yxr.affairs.utils.ToastUtil;
import com.yxr.affairs.utils.UserInfo1;
import com.yxr.affairs.utils.Utils;
import com.yxr.affairs.xtem.EncodeXstream;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONException;
import org.json.JSONObject;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpTransportSE;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;

import butterknife.BindView;
import butterknife.OnClick;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

import static android.content.Context.MODE_PRIVATE;

public class LoginActicity1 extends BaseActivity1 {
    @BindView(R.id.login_account)
    AutoCompleteTextView mAccountView;

    @BindView(R.id.login_password)
    EditText mPasswordView;

    @BindView(R.id.ib_login_user_clear_)
    ImageButton mPhoneClear;

    @BindView(R.id.ib_login_pwd_clear)
    ImageButton mpasswordClear;

    private String mPhone;
    private String mPassword;
    private String result;

    private String SoftVersion;
    private String DataServerIP;
    private String Key;
    private String DataServerPort;
    private String SoftName;
    private String mDeviceid;
    private String mUsercode;
    private String mUserpwd;
    private String mVersion;
    private String mHospitalid;


    private Handler handler;

    private CommonProgressDialog pBar;

    private String content = "";

    private String URL;

    private static final String DOWNLOAD_NAME = "channelWe";

    private final int SHOW_ERROR = 1;
    private Handler mHandler;
    public static void startActivity(Activity activity){
        activity.startActivity(new Intent(activity.getApplicationContext(), LoginActicity1.class));
        activity.overridePendingTransition(R.anim.slide_right_entry, R.anim.hold);
    }

    @Override
    protected int attachLayoutRes() {
        return R.layout.activity_login1;
    }

    @Override
    protected void initViews() {


        EventBus.getDefault().register(this);//注册  注意这里注册，必须这个界面这个方法先注册过了，才能接受到adapter发送的值
        //点击键盘上的回车键触发
        mPasswordView.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView textView, int id, KeyEvent keyEvent) {
                attemptLogin();
                return true;
            }
        });

        mAccountView.addTextChangedListener(mWatcherMobile);
        mPasswordView.addTextChangedListener(mPasswordWatcher);

        String phone = UserInfo1.getUsername();
        if (!TextUtils.isEmpty(phone)) {
            mAccountView.setText(phone);
            mAccountView.setSelection(mAccountView.length());
        }
        handler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                switch (msg.what) {           //进行版本更新
                    case 100:
                        ShowDialog(content); //进行版本更新
                        break;
                }
            }
        };


        mHandler = new Handler(new Handler.Callback() {
            @Override
            public boolean handleMessage(Message msg) {
                int what = msg.what;
                if (SHOW_ERROR == what) {
                    ToastUtil.toast(mContext, "你输入的端口地址有错误，请从新输入");
                }
                return false;
            }
        });
        getMyData();


    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void getEvent(Piye event) {

        getMyData();

    }


    private void getMyData() {

        String url = Constans1.getData(mContext) + "/get_key";
        OkHttpClient okHttpClient = new OkHttpClient();
        final Request request = new Request.Builder()
                .url(url)
                .get()//默认就是GET请求，可以不写
                .build();
        Call call = okHttpClient.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {

                //    mHandler.sendEmptyMessage(SHOW_ERROR);

            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                //    Log.d("DADADAD", "onResponse: " + response.body().string());

                try {
                    String json = response.body().string();
                    JSONObject jsonObject = new JSONObject(json);
                    SoftVersion = jsonObject.getString("SoftVersion"); //版本号
                    Key = jsonObject.getString("Key");   //对应key值
                    DataServerIP = jsonObject.getString("DataServerIP"); //服务器地址
                    DataServerPort = jsonObject.getString("DataServerPort");  //端口号
                    SoftName = jsonObject.getString("SoftName");   //下载的apk
                    mDeviceid=jsonObject.getString("deviceid");
                    mUsercode=jsonObject.getString("usercode");
                    mUserpwd=jsonObject.getString("userpwd");
                    mVersion=jsonObject.getString("version");
                    mHospitalid=jsonObject.getString("hospitalid");

                    SPUtils.getInstance(mContext).put("mdata1", DataServerIP + ":" + DataServerPort);
                    SharedPreferences sharedPreferences = getSharedPreferences("muser", MODE_PRIVATE);
                    SharedPreferences.Editor edit = sharedPreferences.edit();
                    //通过editor对象写入数据
                    edit.putString("SoftVersion", SoftVersion);
                    edit.putString("Key", Key);
                    edit.putString("DataServerIP", DataServerIP);
                    edit.putString("DataServerPort", DataServerPort);
                    edit.putString("SoftName", SoftName);
                    edit.putString("mDeviceid", mDeviceid);
                    edit.putString("mUsercode", mUsercode);
                    edit.putString("mUserpwd", mUserpwd);
                    edit.putString("mVersion", mVersion);
                    edit.putString("mHospitalid", mHospitalid);

                    Log.d("ADADADAD", SoftVersion);

                    //提交数据存入到xml文件中
                    edit.commit();
                    //   URL="http://"+DataServerIP+":"+DataServerPort+"/"+SoftName+"?";
                    //    Log.i("ASASASAS",URL);
                    getUpdae();

                } catch (JSONException e) {
                    e.printStackTrace();


                }

            }
        });

    }

    private void getUpdae() {


        URL = Constans1.getData(mContext) + "/" + SoftName + "?";

        String versionCode = getVersionCode(mContext);
        String code = String.valueOf(versionCode);

        if (!code.equals(SoftVersion)) { //通知进行版本更新
            Message message = new Message();
            message.what = 100;
            handler.sendMessage(message);
        }

    }

    private void ShowDialog(String content) {

        new android.app.AlertDialog.Builder(mContext)
                .setTitle("版本更新")
                .setMessage(content)
                .setPositiveButton("更新", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                        pBar = new CommonProgressDialog(mContext);
                        pBar.setCanceledOnTouchOutside(false);
                        pBar.setTitle("正在下载");
                        /*pBar.setCustomTitle(LayoutInflater.from(
                                MainActivity.this).inflate(
                                R.layout.title_dialog, null));*/
                        pBar.setMessage("正在下载");
                        pBar.setIndeterminate(true);
                        pBar.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
                        pBar.setCancelable(true);
                        // downFile(URLData.DOWNLOAD_URL);
                        final DownloadTask downloadTask = new DownloadTask(
                                mContext);
                        downloadTask.execute(URL);
                        pBar.setOnCancelListener(new DialogInterface.OnCancelListener() {
                            @Override
                            public void onCancel(DialogInterface dialog) {
                                downloadTask.cancel(true);
                            }
                        });
                    }
                })
                .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                })
                .show();
    }

    class DownloadTask extends AsyncTask<String, Integer, String> {

        private Context context;
        private PowerManager.WakeLock mWakeLock;

        public DownloadTask(Context context) {
            this.context = context;
        }

        @Override
        protected String doInBackground(String... sUrl) {
            InputStream input = null;
            OutputStream output = null;
            HttpURLConnection connection = null;
            File file = null;
            try {
                URL url = new URL(sUrl[0]);
                connection = (HttpURLConnection) url.openConnection();
                connection.connect();
                // expect HTTP 200 OK, so we don't mistakenly save error
                // report
                // instead of the file
                if (connection.getResponseCode() != HttpURLConnection.HTTP_OK) {
                    return "Server returned HTTP "
                            + connection.getResponseCode() + " "
                            + connection.getResponseMessage();
                }
                // this will be useful to display download percentage
                // might be -1: server did not report the length
                int fileLength = connection.getContentLength();
                if (Environment.getExternalStorageState().equals(
                        Environment.MEDIA_MOUNTED)) {
                    file = new File(Environment.getExternalStorageDirectory(),
                            DOWNLOAD_NAME);

                    if (!file.exists()) {
                        // 判断父文件夹是否存在
                        if (!file.getParentFile().exists()) {
                            file.getParentFile().mkdirs();
                        }
                    }

                } else {
                    Toast.makeText(mContext, "sd卡未挂载",
                            Toast.LENGTH_LONG).show();
                }
                input = connection.getInputStream();
                Log.i("DADAD", input.toString());
                output = new FileOutputStream(file);
                byte data[] = new byte[4096];
                long total = 0;
                int count;
                while ((count = input.read(data)) != -1) {
                    // allow canceling with back button
                    if (isCancelled()) {
                        input.close();
                        return null;
                    }
                    total += count;
                    Log.i("DADAD11", String.valueOf(total));
                    // publishing the progress....
                    if (fileLength > 0) // only if total length is known
                        publishProgress((int) (total * 100 / fileLength));
                    output.write(data, 0, count);
                    Log.i("DADAD111", String.valueOf(total));

                }
            } catch (Exception e) {
                System.out.println(e.toString());
                return e.toString();

            } finally {
                try {
                    if (output != null)
                        output.close();
                    if (input != null)
                        input.close();
                } catch (IOException ignored) {
                }
                if (connection != null)
                    connection.disconnect();
            }
            return null;
        }

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            // take CPU lock to prevent CPU from going off if the user
            // presses the power button during download
            PowerManager pm = (PowerManager) context
                    .getSystemService(Context.POWER_SERVICE);
            mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK,
                    getClass().getName());
            mWakeLock.acquire();
            pBar.show();
        }

        @Override
        protected void onProgressUpdate(Integer... progress) {
            super.onProgressUpdate(progress);
            // if we get here, length is known, now set indeterminate to false
            pBar.setIndeterminate(false);
            pBar.setMax(100);
            pBar.setProgress(progress[0]);
        }

        @Override
        protected void onPostExecute(String result) {
            mWakeLock.release();
            pBar.setProgress(100);
            pBar.dismiss();
            if (result != null) {

                Toast.makeText(context, "您未打开SD卡权限" + result, Toast.LENGTH_LONG).show();
            } else {
                // Toast.makeText(context, "File downloaded",
                // Toast.LENGTH_SHORT)
                // .show();
                update();
            }

        }


    }

    private void update() {
        //安装应用
        Intent intent = new Intent(Intent.ACTION_VIEW);
        intent.setDataAndType(Uri.fromFile(new File(Environment
                        .getExternalStorageDirectory(), DOWNLOAD_NAME)),
                "application/vnd.android.package-archive");
        startActivity(intent);
    }

    private String getVersionCode(Context mContext) {
        PackageManager packageManager = mContext.getPackageManager();
        try {
            PackageInfo packInfo = packageManager.getPackageInfo(mContext.getPackageName(), 0);
            String version = packInfo.versionName;
            return version;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }

        return null;
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (KeyEvent.KEYCODE_BACK == keyCode) {
            _exit();
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    public void onBackPressed() {
        return;
    }

    private void _exit() {
        if(MainActivity.mMian!=null){

            MainActivity.mMian.finish();
        }
        finish();
    }

    @Override
    public void finish() {
        super.finish();
        overridePendingTransition(R.anim.hold, R.anim.slide_right_exit);
    }

    @OnClick({R.id.login_sign_in, R.id.login_pwd_forget, R.id.ib_login_user_clear_, R.id.ib_login_pwd_clear})
    public void click(View view) {
        switch (view.getId()) {
            case R.id.login_sign_in:
                attemptLogin();
                break;
            case R.id.login_pwd_forget:
                startActivity(new Intent(mContext, AddActivity.class));
                break;
            case R.id.ib_login_user_clear_:
                mAccountView.setText("");
                break;
            case R.id.ib_login_pwd_clear:
                mPasswordView.setText("");
                break;
                default:
                break;
        }
    }

    private void attemptLogin() {

        mPhone = mAccountView.getText().toString();
        mPassword = mPasswordView.getText().toString();
        if (!Utils.isNetworkConnected(mContext)) {
            Toast.makeText(mContext, getString(R.string.network_hint), Toast.LENGTH_SHORT).show();
            return;
        }
        QueryAddressTask queryAddressTask = new QueryAddressTask();
        queryAddressTask.execute(mPhone, mPassword);

    }
    public String getData(String param){


       /*     String WSDL_URI = Constans1.getData(mContext);//wsdl 的uri
        Log.d("FFAFAF",WSDL_URI);
            String namespace = "urn:HyWebServerIntf-IHyWebServer";//namespace
            String methodName = "HyWebServiceIntfMethod";//要调用的方法名称

            SoapObject request = new SoapObject(namespace, methodName);

            com.yxr.haochedai.bean.Param1 param1 = new com.yxr.haochedai.bean.Param1("UserLogin");
            com.yxr.haochedai.bean.Param2 param2 = new com.yxr.haochedai.bean.Param2(mPhone, mPassword);

            Params params = new Params(param1, param2);
            Hywebserviceroot root = new Hywebserviceroot("GetMbUserFunction", SoftVersion, "21644BE1DD5915CDC8CF09E4607789288E3322A0C07D9E9108B89A14FF01CC6644B27E6616F4A17C390445BCA04922B2E7E923B871841BD10C7E5E08B0FDE522", "001", "9999", "123456", "5.0", params);
            XStream xStream = new EncodeXstream("1.0", "gb2312");
            xStream.alias("hywebserviceroot", Hywebserviceroot.class);
            xStream.alias("params", Params.class);
            String xmlDATA = xStream.toXML(root);
            //      Log.e(TAG, "intXmlParam: " + xStream.toXML(root));
            request.addProperty("aXml", xmlDATA);*/

        String    result = null;
        String WSDL_URI ="http://"+DataServerIP+":"+DataServerPort+"/soap/IHyWebServer" ;//wsdl 的uri
        String namespace = "urn:HyWebServerIntf-IHyWebServer";//namespace
        String methodName = "HyWebServiceIntfMethod";//要调用的方法名称

        SoapObject request = new SoapObject(namespace, methodName);

        String de= "<hywebserviceroot>" +
                "<funname>GetMbUserFunction</funname>" +
                "<hospitalid>"+mHospitalid+"</hospitalid>" +
                "    <key>"+Key+"</key>" +
                "    <deviceid>"+mDeviceid+"</deviceid>" +
                "    <usercode>"+mUsercode+"</usercode>" +
                "    <userpwd>"+mUserpwd+"</userpwd>" +
                "    <version>"+mVersion+"</version>" +
                "    <params>" +
                "     <param1><sFunName>UserLogin</sFunName></param1>" +
                "     <param2><sYHBH>"+mPhone+"</sYHBH><sYHMM>"+mPassword+"</sYHMM></param2>"+
                "    </params>" +
                "</hywebserviceroot>";

        request.addProperty("aXml", de);
            //创建SoapSerializationEnvelope 对象，同时指定soap版本号(之前在wsdl中看到的)

            try {
                SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapSerializationEnvelope.VER11);
                envelope.bodyOut = request;//由于是发送请求，所以是设置bodyOut
                envelope.dotNet = true;//由于是.net开发的webservice，所以这里要设置为true
                HttpTransportSE httpTransportSE = new HttpTransportSE(WSDL_URI);
                httpTransportSE.debug = false;
                httpTransportSE.call("urn:HyWebServerIntf-IHyWebServer#HyWebServiceIntfMethod", envelope);//调用

                // 获取服务器响应返回的SOAP消息
                SoapObject object = (SoapObject) envelope.bodyIn;
                     result = object.getProperty(0).toString();
           //     Log.e("DSDSDS", result);
                return result;

            } catch (Exception e) {
                Log.e("TAG", "getData: "+e );
            }
            return result;
        }


    class QueryAddressTask extends AsyncTask<String, Integer, String> {
        @Override
        protected String doInBackground(String... params) {
            // 查询手机号码（段）信息*/
            try {
                result = getData(params[0]);


            } catch (Exception e) {

                e.printStackTrace();
            }
            //将结果返回给onPostExecute方法
            return result;
        }

        @Override
        //此方法可以在主线程改变UI
        protected void onPostExecute(String result) {

            if (result != null) {
                // 将WebService返回的结果显示在TextView中
                XStream xStream2 = new EncodeXstream("1.0", "gb2312");
                xStream2.alias("result", Data.class);
                xStream2.useAttributeFor(Param1.class, "size");
                xStream2.addImplicitCollection(Param1.class, "storeditems");
                xStream2.alias("storeditem", Storeditem.class);
                Data data = (Data) xStream2.fromXML(result);

                Log.e("TAG", "status: " + data.getStatus());
                Log.e("TAG", "errorinfo: " + data.getErrorinfo());
                Log.e("TAG","successinfo"+data.getSuccessinfo());
                Log.e("TAG", "param1 size: " + data.getSuccessinfo().getParam1().getSize());


                if(data.getSuccessinfo().getParam1().getSize().equals("0")){

                    ToastUtil.toast(mContext,"编号或者密码错误请从新输入");
                }else{

                    ToastUtil.toast(mContext, "登录成功");
                    UserInfo1.setUserInfo(mPhone, mPassword);
                    EventBus.getDefault().post(0);
                    finish();
                }
            }else {

                ToastUtil.toast(mContext,"你还没有输入的端口地址");
            }


        }
    }


    private TextWatcher mWatcherMobile = new TextWatcher() {

        @Override
        public void beforeTextChanged(CharSequence charSequence, int i, int i1,
                                      int i2) {
        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            if (s == null || s.length() == 0) {
                mPhoneClear.setVisibility(View.GONE);
            } else {
                mPhoneClear.setVisibility(View.VISIBLE);
            }

            if (s == null || s.length() == 0) {
                return;
            }
        //    StringBuilder sb = new StringBuilder();
           /* for (int i = 0; i < s.length(); i++) {
                if (i != 3 && i != 8 && s.charAt(i) == ' ') {
                    continue;
                } else {
                    sb.append(s.charAt(i));
                    if ((sb.length() == 4 || sb.length() == 9) && sb.charAt(sb.length() - 1) != ' ') {
                        sb.insert(sb.length() - 1, ' ');
                    }
                }
            }*/
           /* if (!sb.toString().equals(s.toString())) {
                int index = start + 1;
                if (sb.charAt(start) == ' ') {
                    if (before == 0) {
                        index++;
                    } else {
                        index--;
                    }
                } else {
                    if (before == 1) {
                        index--;
                    }
                }
                mAccountView.setText(sb.toString());
                mAccountView.setSelection(index);
            }*/
        }

        @Override
        public void afterTextChanged(Editable editable) {

        }
    };

    private TextWatcher mPasswordWatcher = new TextWatcher() {

        @Override
        public void beforeTextChanged(CharSequence charSequence, int i, int i1,
                                      int i2) {
        }

        @Override
        public void onTextChanged(CharSequence s, int i, int i1, int i2) {
            if (s == null || s.length() == 0) {
                mpasswordClear.setVisibility(View.GONE);
            } else {
                mpasswordClear.setVisibility(View.VISIBLE);
            }
        }

        @Override
        public void afterTextChanged(Editable editable) {
            //
        }
    };
    @Override
    protected void updateViews(boolean isRefresh) {

    }



    @Override
    protected void onError_(Throwable e) {

    }

    @Override
    protected void onCancel_() {

    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);//注销
    }

}
